package com.example.medicinebox.ui.screens

import android.text.Layout
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RangeSlider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TimeInput
import androidx.compose.material3.TimePickerState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.LineHeightStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.medicinebox.model.ClockAtomic
import java.util.Calendar

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(
    uiState: MbUiState,
    checked: List<MutableState<Boolean>>,
    clockList: List<ClockAtomic>,
    onMedicineDialogShow: (Int) -> Unit,
    onMedicineDialogClose: () -> Unit,
    onTimePickerShow: () -> Unit,
    onTimePickerClose: () -> Unit,
    onTimeAdd: (TimePickerState) -> Unit,
    onRemoveClock: (ClockAtomic) -> Unit,
    onChooseBox: (Int) -> Unit,
    medicineNameList: List<MutableState<String?>>,
    onAddMedicineName: () -> Unit,
    medicineNameInput: String,
    onMedicineNameInput: (String) -> Unit,
    modifier: Modifier = Modifier,
    onAdjustDialogClose: () -> Unit,
    onAdjustDialogConfirm: (ClosedFloatingPointRange<Float>, ClosedFloatingPointRange<Float>) -> Unit,
) {
    var tempSlider by remember { mutableStateOf(15f .. 30f) }
    var humiSlider by remember { mutableStateOf(40f .. 60f) }

    if (uiState.showMedicineDialog) {
        MedicineNameReviseDialog(onMedicineDialogClose, onAddMedicineName) {
            OutlinedTextField(
                value = medicineNameInput,
                onValueChange = { onMedicineNameInput(it) },
                label = { Text("输入药品名称") }
            )
        }
    }
    if (uiState.showAdjustDialog) {
        AdjustDialog(
            onAdjustDialogClose,
            { onAdjustDialogConfirm(tempSlider, humiSlider) }
        ) {
            Column {
                Text(
                    text = "设置温度阈值范围",
                    fontWeight = FontWeight.Bold,
                    fontSize = 18.sp,
                    modifier = Modifier.padding(bottom = 10.dp)
                )
                RangeSlider(
                    value = tempSlider,
                    onValueChange = { range -> tempSlider = range },
                    valueRange = 0f..50f,
                    onValueChangeFinished = {
                        // launch some business logic update with the state you hold
                        // viewModel.updateSelectedSliderValue(sliderPosition)
                    },
                )
                Text(
                    text = "%.1f℃ -> %.1f℃".format(
                        tempSlider.start,
                        tempSlider.endInclusive
                    ),
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = TextAlign.Right
                )

                Text(
                    text = "设置湿度阈值范围",
                    fontWeight = FontWeight.Bold,
                    fontSize = 18.sp,
                    modifier = Modifier.padding(top = 30.dp ,bottom = 10.dp)
                )
                RangeSlider(
                    value = humiSlider,
                    onValueChange = { range -> humiSlider = range },
                    valueRange = 0f..100f,
                    onValueChangeFinished = {
                        // launch some business logic update with the state you hold
                        // viewModel.updateSelectedSliderValue(sliderPosition)
                    },
                )
                Text(
                    text = "%.0f -> %.0f".format(
                        humiSlider.start,
                        humiSlider.endInclusive
                    ),
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = TextAlign.Right
                )
            }
        }
    }
    Box(
        modifier = modifier
            .fillMaxSize()
            .padding(20.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.TopStart)
                .padding(bottom = 360.dp) // 为底部区域预留空间
        ) {
            Text(
                textAlign = TextAlign.Center,
                modifier = Modifier.fillMaxWidth(),
                text = "当前温度：%.1f℃，湿度：%d".format(
                    uiState.temp, uiState.humi
                ),
                fontSize = 20.sp
            )
            //HorizontalDivider()
            ClockAddInterface(
                uiState.showTimePicker,
                checked,
                clockList,
                onTimePickerShow,
                onTimePickerClose,
                onTimeAdd,
                onRemoveClock,
                onChooseBox
            )
            HorizontalDivider()
        }
        MedicineBoxesArea(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.BottomCenter),
            onMedicineDialogShow,
            medicineNameList,
            uiState.tempRange,
            uiState.humiRange,
            uiState.alarmAttach
        )
    }
}

@Composable
fun AdjustDialog(
    onDismiss: () -> Unit,
    onConfirm: () -> Unit,
    content: @Composable () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        dismissButton = {
            TextButton(onClick = { onDismiss() }) {
                Text("取消")
            }
        },
        confirmButton = {
            TextButton(onClick = { onConfirm() }) {
                Text("确定")
            }
        },
        text = { content() }
    )
}

@Composable
fun MedicineBoxesArea(
    modifier: Modifier = Modifier,
    onMedicineDialogShow: (Int) -> Unit,
    medicineNameList: List<MutableState<String?>>,
    tempRange: ClosedFloatingPointRange<Float>,
    humiRange: ClosedFloatingPointRange<Float>,
    alarmAttach: Boolean
) {
    Column(
        modifier = modifier.height(280.dp).padding(top = 8.dp)
    ) {
        Text(
            text = "温度阈值：%.1f℃ -> %.1f℃".format(
                tempRange.start, tempRange.endInclusive
            ),
            fontSize = 20.sp,
        )
        Text(
            text = "湿度阈值：%.0f%% -> %.0f%%".format(
                humiRange.start, humiRange.endInclusive
            ),
            fontSize = 20.sp,
        )
        repeat(3) { rowIndex ->
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f),
                horizontalArrangement = Arrangement.spacedBy(1.dp)
            ) {
                repeat(3) { colIndex ->
                    MedicineBoxBin(
                        index = rowIndex * 3 + colIndex + 1,
                        modifier = Modifier
                            .weight(1f)
                            .fillMaxHeight(),
                        medicineName = medicineNameList[rowIndex * 3 + colIndex].value,
                        onMedicineDialogShow = onMedicineDialogShow,
                        // 闹钟到的时候，（1,1）的格子变成绿色
                        willColorChanged = alarmAttach and ((rowIndex == 1) and (colIndex == 1))
                    )
                }
            }
        }
    }
}

@Composable
fun MedicineBoxBin(
    modifier: Modifier = Modifier,
    index: Int = 1,
    medicineName: String?,
    onMedicineDialogShow: (Int) -> Unit,
    willColorChanged: Boolean
) {
    Button(
        modifier = modifier
            .padding(4.dp),
        onClick = {
            onMedicineDialogShow(index - 1)
        },
        shape = RectangleShape,
        colors = if (willColorChanged) {
            ButtonDefaults.buttonColors(
                containerColor = Color(180, 250, 150),
                contentColor = MaterialTheme.colorScheme.primary
            )
        } else {
            ButtonDefaults.buttonColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                contentColor = MaterialTheme.colorScheme.primary
            )
        }
    ) {
        Column(
            modifier.fillMaxSize()
        ) {
            Text(
                text = "$index",
                fontSize = 20.sp,
                textAlign = TextAlign.Left
            )
            medicineName?.let { Text(it) }
        }
    }
}

@Composable
fun MedicineNameReviseDialog(
    onDismiss: () -> Unit,
    onConfirm: () -> Unit,
    content: @Composable () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        dismissButton = {
            TextButton(onClick = { onDismiss() }) {
                Text("取消")
            }
        },
        confirmButton = {
            TextButton(onClick = { onConfirm() }) {
                Text("确定")
            }
        },
        text = { content() }
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ClockAddInterface(
    willShowTimePicker: Boolean,
    checkedState: List<MutableState<Boolean>>,
    clockList: List<ClockAtomic>,
    onTimePickerShow: () -> Unit,
    onTimePickerClose: () -> Unit,
    onTimeAdd: (TimePickerState) -> Unit,
    onRemoveClock: (ClockAtomic) -> Unit,
    onChooseBox: (Int) -> Unit,
    modifier: Modifier = Modifier
) {
    val currentTime = Calendar.getInstance()

    val timePickerState = rememberTimePickerState(
        initialHour = currentTime.get(Calendar.HOUR_OF_DAY),
        initialMinute = currentTime.get(Calendar.MINUTE),
        is24Hour = true,
    )

    Column(
        modifier = modifier.padding(top = 20.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "设置闹钟",
                fontWeight = FontWeight.Bold,
                fontSize = 20.sp,
                modifier = Modifier.weight(1f)
            )
            Button(onClick = onTimePickerShow) {
                Text("添加")
            }
        }
        ClocksList(
            list = clockList,
            onRemoveClock = onRemoveClock
        )
    }

    if (willShowTimePicker) {
        TimePickerDialog(
            onDismiss = onTimePickerClose,
            onConfirm = { onTimeAdd(timePickerState) }
        ) {
            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                TimeInput(
                    state = timePickerState
                )
                Text(
                    "选择药物(1~9个单选框)",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold
                )
                repeat(3) { rowIndex ->
                    Row {
                        repeat(3) { checkedIndex ->
                            Checkbox(
                                onCheckedChange = { onChooseBox(rowIndex * 3 + checkedIndex) },
                                checked = checkedState[rowIndex * 3 + checkedIndex].value
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun ClocksList(
    list: List<ClockAtomic>,
    onRemoveClock: (ClockAtomic) -> Unit,
    modifier: Modifier = Modifier
) {
    LazyColumn(modifier = modifier) {
        items(
            items = list,
            key = { clockAtomic -> list.indexOf(clockAtomic) }
        ) { clockAtomic ->
            ClockItem(
                clockID = list.indexOf(clockAtomic) + 1,
                clockTimeSet = clockAtomic.getTimeString(),
                medicineSet = clockAtomic.getMedicines(),
                onRemoveClock = { onRemoveClock(clockAtomic) }
            )
        }
    }
}

@Composable
fun ClockItem(
    modifier: Modifier = Modifier,
    clockID: Int,
    clockTimeSet: String,
    medicineSet: String,
    onRemoveClock: () -> Unit
) {
    HorizontalDivider()
    Row(
        modifier = modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            modifier = Modifier.weight(1f),
            text = "#${clockID}   $clockTimeSet"
        )
        Text(
            text = medicineSet
        )
        TextButton(onClick = onRemoveClock) {
            Text("删除")
        }
    }
    HorizontalDivider()
}

@Composable
fun TimePickerDialog(
    onDismiss: () -> Unit,
    onConfirm: () -> Unit,
    content: @Composable () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        dismissButton = {
            TextButton(onClick = { onDismiss() }) {
                Text("取消")
            }
        },
        confirmButton = {
            TextButton(onClick = { onConfirm() }) {
                Text("确定")
            }
        },
        text = { content() }
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun MainScreenPreview() {

    val uiState = MbUiState(
        showTimePicker = false,
        showMedicineDialog = false,
        namedIndex = 1,
        appTitle = "智能药箱",
        temp = 32.3f,
        humi = 50,
        showAdjustDialog = false,
        alarmAttach = true
    )

    /* 9 种药品名称 */
    val medicineName: List<MutableState<String?>> = List(9) { mutableStateOf("") }

    val clocks = remember { mutableStateListOf<ClockAtomic>() }

    val checked = List(9) { mutableStateOf(false) }

    /* 药品输入框 */
    val medicineNameInput by remember { mutableStateOf("") }


    MainScreen(
        uiState = uiState,
        checked = checked,
        clockList = clocks,
        onMedicineDialogShow = { },
        onMedicineDialogClose = { },
        onTimePickerShow = { },
        onTimePickerClose = { },
        onTimeAdd = { },
        onRemoveClock = { },
        onChooseBox = { },
        medicineNameList = medicineName,
        onAddMedicineName = { },
        medicineNameInput = medicineNameInput,
        onMedicineNameInput = { },
        modifier = Modifier,
        onAdjustDialogClose = { },
        onAdjustDialogConfirm = { valueA, valueB -> }
    )

}
